import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:intl/intl.dart';
import 'package:redux/redux.dart';
import 'package:stock_check/common/dao/TasksDao.dart';
import 'package:stock_check/common/db/SqliteManage.dart';
import 'package:stock_check/common/db/TaskModel.dart';
import 'package:stock_check/common/model/app.dart';
import 'package:stock_check/common/model/taskItem.dart';
import 'package:stock_check/common/model/taskItemDetail.dart';
import 'package:stock_check/common/redux/reduxStore.dart';
import 'package:stock_check/common/utils/NavigatorUtils.dart';
import 'package:stock_check/widget/CommonsWidget.dart';
import 'package:stock_check/widget/MyScaffold.dart';

/// 盘点任务
class CheckWork extends StatefulWidget {
  @override
  _CheckWorkState createState() => _CheckWorkState();
}

class _CheckWorkState extends State<CheckWork> {
  bool checkAll = false;
  List<TaskItem> list = new List();
  final formatter = new DateFormat('yyyy-MM-dd');

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  // 数据下载
  _downLoadData() async{
    String ids = "";
    List<TaskItem> needDownLoad = new List();
    for(int i=0;i<list.length;i++){
      if (list[i].check == true) {
        list[i].check = false;
        needDownLoad.add(list[i]);
        ids += list[i].id.toString()+",";
      }
    }

    ids = ids.substring(0,ids.length-1);

    if (ids.length == 0) {
      Fluttertoast.showToast(msg: "暂无可下载数据！");
      return;
    }
    CommonsWidget.showLoadingDialog(context,'下载中...');
    DataBase dataBase = new DataBase();
    // 下载数据
    List<TaskDetailItem> taskDetails = await TasksDao.downLoad(needDownLoad, ids);
    if(taskDetails!=null&&taskDetails.length>0){
      List<TaskDetailItem> oldList = new List();
      String currentTime = formatter.format(DateTime.now());
      TaskModel taskModel = await dataBase.getOneTaskByUpdateTime(currentTime);
      // 更新局部数据
      if(taskModel!=null&&taskModel.jsonTxt!=null){
        var oldData = json.decode(taskModel.jsonTxt);
        for(int i=0;i<oldData.length;i++){
          oldList.add(TaskDetailItem.fromJson(oldData[i]));
        }
        List<TaskDetailItem> temp = new List();
        taskDetails.forEach((f){
          bool flag = true;
          oldList.forEach((m){
            if(f.taskId == m.taskId){
              flag = false;
            }
          });
          if(flag) temp.add(f);
        });
        oldList = oldList+temp;
        taskModel.jsonTxt = json.encode(oldList);
        await dataBase.updateTaskModel(taskModel);
      }else{
        taskModel = new TaskModel();
        taskModel.updateTime = currentTime;
        taskModel.jsonTxt = json.encode(taskDetails);
        await dataBase.deleteTable();
        await dataBase.insertTaskModel(taskModel);
      }
    }
    setState(() {
      checkAll = false;
    });
    Navigator.of(context,rootNavigator: true).pop(context);
  }

  Widget _renderHead(App appInfo) {
    bool online = appInfo.netWork.index != 2;
    Color accentColor = Theme.of(context).primaryColor;
    accentColor =
        accentColor == Color(0xff212121) ? Colors.greenAccent : accentColor;
    return Card(
        margin: EdgeInsets.zero,
        shape: RoundedRectangleBorder(),
        elevation: .7,
        child: ListTile(
            contentPadding:
                EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
            leading: Checkbox(
                value: checkAll,
                onChanged: (bool) {
                  setState(() {
                    checkAll = bool;
                    list.forEach((TaskItem w) {
                      if (w.ifDownloadStr != '已下载') w.check = bool;
                    });
                  });
                }),
            title: Text("全选"),
            trailing: RaisedButton(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20.0)),
              onPressed: online ? _downLoadData : null,
              elevation: .2,
              color: accentColor,
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Icon(
                    Icons.cloud_download,
                    color: Colors.white,
                  ),
                  Text(
                    online ? " 下载" : " 离线",
                    style: TextStyle(color: Colors.white),
                  ),
                ],
              ),
            )));
  }

  // 刷新数据
  Future<Null> _pullToRefresh() async {
    Fluttertoast.showToast(msg: "数据已刷新!");
    return null;
  }

  Widget _renderList() {
    if(list.length>0)
      return RefreshIndicator(
          onRefresh: _pullToRefresh,
          child: Scrollbar(
              child: ListView.separated(
            shrinkWrap: true,
            itemCount: list.length,
            separatorBuilder: (context, index) {
              return Divider();
            },
            itemBuilder: (context, index) {
              return Column(
                children: <Widget>[
                  ListTile(
                    dense: true,
                    onTap: list[index].ifDownloadStr == '已下载' ? () {
                      NavigatorUtils.goCheckList(context, list[index]);
                          } : null,
                    contentPadding:
                        EdgeInsets.symmetric(horizontal: 10.0, vertical: 0.0),
                    leading: Checkbox(
                        value: list[index].check,
                        onChanged: (bool) {
                          setState(() {
                            list[index].check =
                                list[index].ifDownloadStr == '已下载' ? false : bool;
                          });
                        }),
                    title: Text(
                      "${list[index].taskName}",
                      style: TextStyle(
                          color: list[index].ifDownloadStr == '未下载'
                              ? Colors.grey
                              : Theme.of(context).accentColor,
                          fontSize: 15.0),
                    ),
                    trailing: list[index].ifDownloadStr != '未下载'
                        ? CommonsWidget.hasDownLoad
                        : CommonsWidget.notDownload,
                  )
                ],
              );
            },
          )));
    else
      return CommonsWidget.getNullData();
  }

  Store<StockState> store;

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
    store = StoreProvider.of(context);
    list = store.state.worksInfo.tasks;
  }

  @override
  Widget build(BuildContext context) {
    return StoreBuilder<StockState>(builder: (context, store) {
      App appInfo = store.state.appInfo;
      return MyScaffold(
          title: Text("盘点任务"),
          store: store,
          noLeading: true,
          child: Column(
            children: [
              Column(
                children: [_renderHead(appInfo)],
              ),
              Padding(
                padding: EdgeInsets.only(top: 10.0),
              ),
              Expanded(
                child: _renderList(),
              )
            ],
          ));
    });
  }
}
